package com.ea.admin.service.impl;

import com.ea.admin.pojo.vo.file.FileInfoVo;
import com.ea.admin.service.FileService;
import com.ea.admin.service.ReportFileService;
import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;

/**
 * 报告文件服务实现类
 * @author luxl
 * date:2025-06-20
 */
@Service
public class ReportFileServiceImpl implements ReportFileService {

    private static final Logger logger = LoggerFactory.getLogger(ReportFileServiceImpl.class);

    @Resource
    FileService fileService;

    @Override
    public String getImageAsBase64(String md5) {
        try {
            // 如果md5为空或null，直接返回默认头像
            if (md5 == null || md5.trim().isEmpty()) {
                return getDefaultAvatarBase64();
            }
            
            // 获取文件路径
            FileInfoVo fileInfo = fileService.getFileInfo(md5);
            String type = fileInfo.getType();
            String filePath = fileService.getPathByType(type) + md5 + File.separator + md5 + "." + type;
    
            // 读取图片文件
            File imageFile = new File(filePath);
            if (!imageFile.exists()) {
                logger.warn("图片文件不存在: {}，使用默认头像", filePath);
                return getDefaultAvatarBase64();
            }
    
            // 读取文件字节
            byte[] imageBytes;
            try (FileInputStream fis = new FileInputStream(imageFile);
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }
                imageBytes = baos.toByteArray();
            }
    
            // 转换为Base64
            return Base64.encodeBase64String(imageBytes);
    
        } catch (BizException e) {
            // 如果是文件不存在的业务异常，返回默认头像
            if (ErrorCode.SYSTEM_RESOURCE_ERROR_FILE_NOT_EXISTS.equals(e.getErrorCode())) {
                logger.warn("文件不存在，md5: {}，使用默认头像", md5);
                return getDefaultAvatarBase64();
            }
            logger.error("获取图片Base64编码失败，md5: {}", md5, e);
            return getDefaultAvatarBase64();
        } catch (Exception e) {
            logger.error("获取图片Base64编码失败，md5: {}", md5, e);
            return getDefaultAvatarBase64();
        }
    }

    /**
     * 获取默认头像的Base64编码
     * @return 默认头像的Base64字符串
     */
    private String getDefaultAvatarBase64() {
        try {
            String defaultAvatarPath = "Resources4PDFGeneration/defaultAvatar.jpg";

            // 使用ClassPathResource加载资源文件
            ClassPathResource resource = new ClassPathResource(defaultAvatarPath);
            if (!resource.exists()) {
                logger.warn("默认头像文件不存在: {}", defaultAvatarPath);
                return "";
            }

            byte[] imageBytes;
            try (InputStream inputStream = resource.getInputStream();
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }
                imageBytes = baos.toByteArray();
            }

            return Base64.encodeBase64String(imageBytes);

        } catch (Exception e) {
            logger.error("获取默认头像失败", e);
            return "";
        }
    }

}